package com.jps.transactional;

import com.jps.entity.Order;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.apache.rocketmq.spring.support.RocketMQHeaders;
import org.springframework.messaging.Message;

/**
 * create by lenovo 2020/10/2
 *
 * STEP 2
 */

@RocketMQTransactionListener(txProducerGroup = "OrderTransactionGroup")
public class TransactionMsgListener implements RocketMQLocalTransactionListener {
    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message message, Object o) {
        System.out.println("**********事务执行...****************");
        // 获取事务ID
         Object transactionId = message.getHeaders().get(RocketMQHeaders.TRANSACTION_ID);
        System.out.println("execute事务ID="+transactionId);
        boolean result = this.saveOrder((Order) message.getPayload(), transactionId);


        return result?RocketMQLocalTransactionState.COMMIT:RocketMQLocalTransactionState.ROLLBACK;
    }

    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message message) {
        System.out.println("**********事务检查...****************");
        // 获取事务ID
        Object transactionId = message.getHeaders().get(RocketMQHeaders.TRANSACTION_ID);
        System.out.println("check事务ID="+transactionId);
        if (isSuccess(transactionId)){
            return RocketMQLocalTransactionState.COMMIT;
        }

        return RocketMQLocalTransactionState.ROLLBACK;
    }

    private boolean saveOrder(Order order,Object transactionId){
        // 将事务ID设置在唯一键
        // 调用数据库 insert into

        return true;
    }

    private boolean isSuccess(Object transactionId){
        // 查询数据库订单表
        return true;
    }
}
